package org.zy.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import org.zy.core.Message;

public class RealHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) {
        // 读取真实服务器数据
        System.out.println("读取真实服务器数据");

        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        Message msg = new Message(Message.TYPE_TRANSFER, bytes);

        String visitorId = ctx.channel().attr(ClientChannelManager.VISITOR_ID).get();

        if (visitorId == null || visitorId.length() == 0) {
            return;
        }

        Channel proxyChannel = ClientChannelManager.VISITOR_CHANNEL_MAP.get(visitorId);
        if (null != proxyChannel) {
            proxyChannel.writeAndFlush(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String visitorId = ctx.channel().attr(ClientChannelManager.VISITOR_ID).get();
        if (visitorId == null || visitorId.length() == 0) {
            super.channelInactive(ctx);
            return;
        }
        Channel proxyChannel = ClientChannelManager.VISITOR_CHANNEL_MAP.get(visitorId);
        if (proxyChannel != null) {
            Message myMsg = new Message(Message.TYPE_DISCONNECT, visitorId.getBytes());
            proxyChannel.writeAndFlush(myMsg);
        }

        super.channelInactive(ctx);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        String visitorId = ctx.channel().attr(ClientChannelManager.VISITOR_ID).get();
        if (visitorId == null || visitorId.length() == 0) {
            super.channelWritabilityChanged(ctx);
            return;
        }

        Channel proxyChannel = ClientChannelManager.VISITOR_CHANNEL_MAP.get(visitorId);
        if (proxyChannel != null) {
            proxyChannel.config().setOption(ChannelOption.AUTO_READ, ctx.channel().isWritable());
        }

        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}